package com.yourcompany.service.storage;

import com.yourcompany.api.storage.StorageService;
import com.yourcompany.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service("localStorageService")
public class LocalStorageService implements StorageService {

    @Value("${storage.local.path}")
    private String storagePath;
    
    @Value("${storage.local.domain}")
    private String domain;

    @Override
    public String upload(MultipartFile file, String path) {
        try {
            return upload(file.getInputStream(), path, file.getContentType());
        } catch (IOException e) {
            throw new BusinessException("文件上传失败"+ e);
        }
    }

    @Override
    public String upload(InputStream inputStream, String path, String contentType) {
        try {
            File directory = new File(storagePath + File.separator + path).getParentFile();
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            Path targetPath = Paths.get(storagePath + File.separator + path);
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            return getFileUrl(path);
        } catch (IOException e) {
            throw new BusinessException("文件上传失败:" + e);
        }
    }

    @Override
    public void delete(String path) {
        try {
            Path filePath = Paths.get(storagePath + File.separator + path);
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            throw new BusinessException("文件删除失败:" + e);
        }
    }

    @Override
    public String getFileUrl(String path) {
        return domain + "/" + path;
    }
} 